/**
 * Created by LiYang on 16-9-27 下午2:07.
 *
 */

package com.example.db.mapper;

import android.database.Cursor;

import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class RowMapperHandler<T> {
    public abstract T rowMapper(Cursor cursor) throws SQLException;

    protected final String getFieldName(Cursor cursor, int index) throws SQLException {
        return toHump(getMapName(cursor, index));
    }

    protected final String getMapName(Cursor cursor, int index) throws SQLException {
        return cursor.getColumnName(index);
    }

    /**
     * 将下划线风格替换为驼峰风格
     */
    protected final String toHump(String str) {
        Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
        StringBuilder builder = new StringBuilder(str);
        for (int i = 0; matcher.find(); i++) {
            builder.replace(matcher.start() - i, matcher.end() - i, matcher
                    .group().substring(1).toUpperCase());
        }
        if (Character.isUpperCase(builder.charAt(0))) {
            builder.replace(0, 1,
                    String.valueOf(Character.toLowerCase(builder.charAt(0))));
        }
        return builder.toString();
    }
}
